//
//  ImageScrollView.mm
//  AudiHistory
//
//  Created by niko on 11-8-20.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ImageScrollView.h"
#import "TilingView.h"
#import "CPageDataStruct.h"

@implementation ImageScrollView
@synthesize nIndex = m_nIndex;

- (id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame])) {
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.bouncesZoom = YES;
        //self.decelerationRate = UIScrollViewDecelerationRateFast;
        self.delegate = self;        
    }
    return self;
}

- (void)dealloc
{
	[m_pLayer0 Clear];
	[m_pLayer0 removeFromSuperview];
	
	RELEASE_OBJECT(m_pLayer0);
    [super dealloc];
}

#pragma mark -
#pragma mark UIScrollView delegate methods

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return m_pLayer0;
}

- (void)SetMaxMinZoomScalesForCurrentBounds
{
    CGSize boundsSize = self.bounds.size;
    CGSize imageSize = m_pLayer0.bounds.size;
    
    // calculate min/max zoomscale
    CGFloat xScale = boundsSize.width / imageSize.width;    // the scale needed to perfectly fit the image width-wise
    CGFloat yScale = boundsSize.height / imageSize.height;  // the scale needed to perfectly fit the image height-wise
    CGFloat minScale = MIN(xScale, yScale);                 // use minimum of these to allow the image to become fully visible
    
    // on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the
    // maximum zoom scale to 0.5.
    CGFloat maxScale = 1.0 / [[UIScreen mainScreen] scale];
    
    // don't let minScale exceed maxScale. (If the image is smaller than the screen, we don't want to force it to be zoomed.) 
    if (minScale > maxScale) {
        minScale = maxScale;
    }
    
    self.maximumZoomScale = maxScale;
    self.minimumZoomScale = minScale;
}

- (void)LoadPage:(int)nIndex
{
	[m_pLayer0 Clear];
	[m_pLayer0 removeFromSuperview];
	RELEASE_OBJECT(m_pLayer0);
	
	// reset our zoomScale to 1.0 before doing any further calculations
    self.zoomScale = 1.0;
	//左图片
	
	CPageDataStruct *pPageDataStruct = [CPageDataStructTable GetPageDataByPagenum:nIndex];
	
	if (nil == pPageDataStruct)
	{
		return;
	}
	
	UIImage *imageL = [[UIImage alloc] initWithContentsOfFile:fullPathFromRelativePath(pPageDataStruct.strImageL)];
	
	CGSize imageSize = CGSizeMake(imageL.size.width * 2, imageL.size.height);
	
	// make a new UIImageView for the new image
    m_pLayer0 = [[TilingView alloc] initWithIndex:m_nIndex size:imageSize];
    [self addSubview:m_pLayer0];
	
	self.contentSize = imageSize;
	[self SetMaxMinZoomScalesForCurrentBounds];
    self.zoomScale = self.minimumZoomScale;
	
	[m_pLayer0 Load];
	
	RELEASE_OBJECT(imageL);
}

@end
